// import { login, logout, getInfo } from '@/api/user'
import { changePwd, getInfo, login, logoutById } from '@/api/admin';
import { resetRouter } from '@/router';
import { getToken, removeToken, setToken } from '@/utils/auth';

const getDefaultState = () => {
  return {
    id: undefined,
    username: '',
    nickName: '',
    deptId: undefined,
    token: getToken(),
    roles: [],
    openId: undefined,
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_ID: (state, id) => {
    state.id = id;
  },
  SET_USERNAME: (state, username) => {
    state.username = username;
  },
  SET_NICKNAME: (state, nickname) => {
    state.nickName = nickname;
  },
  SET_DEPTID: (state, deptId) => {
    state.deptId = deptId;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_OPENID: (state, openId) => {
    state.openId = openId;
  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      // 调api发验证请求，并获取用户信息
      login({ username: username.trim(), password: password })
        .then(response => {
          const { status, error, message, data } = response.data;
          if (status === 20000) {
            if (data.isFrozen === 1) {
              reject(new Error('400'));
            } else {
              commit('SET_TOKEN', data.token);
              commit('SET_ID', data.id);
              commit('SET_USERNAME', data.username);
              commit('SET_NICKNAME', data.nickName);
              commit('SET_DEPTID', data.deptId);
              commit('SET_OPENID', parseInt(data.openId));
              commit('SET_ROLES', []);
              setToken(data.token);
              resolve(data.deptId);
            }
            // if (data.deptId === 111) {
            //   resolve(data.openId)
            // } else {
            //   resolve()
            // }
          } else {
            console.log(message || error);
            reject(message || error);
          }
        })
        .catch(error => {
          console.log(error);
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const dept = state.deptId;
      if (dept) {
        commit('SET_ROLES', [dept + '']);
        resolve([dept + '']);
      } else {
        const token = getToken();
        if (token && token.length > 0) {
          // 通过token调api获取
          getInfo().then(res => {
            const { status, error, data } = res.data;
            if (status === 20000) {
              commit('SET_TOKEN', data.token);
              commit('SET_ID', data.id);
              commit('SET_USERNAME', data.username);
              commit('SET_NICKNAME', data.nickName);
              commit('SET_DEPTID', data.deptId);
              commit('SET_OPENID', parseInt(data.openId));
              commit('SET_ROLES', [data.deptId + '']);
              setToken(data.token);
              resolve([data.deptId + '']);
            } else {
              reject(error);
            }
          });
        } else {
          // 无token，重新登录
          reject(new Error('请重新登录'));
        }
      }
    });
  },

  changePwd({ state }, password) {
    return new Promise((resolve, reject) => {
      changePwd({ username: state.username, password })
        .then(response => {
          // console.log(response)
          const { status, error } = response.data;
          // console.log(status)
          // console.log(data)
          if (status === 20000) {
            resolve();
          } else {
            console.log(error);
            reject(error);
          }
        })
        .catch(error => {
          console.log(error);
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logoutById(state.username)
        .then(res => {
          removeToken(); // must remove  token  first
          resetRouter();
          commit('RESET_STATE');
          resolve(res);
        })
        .catch(err => {
          resolve();
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken(); // must remove  token  first
      commit('RESET_STATE');
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
